package vn.sms.lazylove;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import vn.sms.lazylove.database.DataStore;
import vn.sms.lazylove.object.SchedulerSMSItem;
import vn.sms.lazylove.object.Sms;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View.OnClickListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class UpdateSmsActivity extends Activity {

	private Activity mActivity;
	private Context mContext;
	private Bundle b;
	TextView txt_select_week, txt_select_time, txt_select_sms,
			txt_select_contact, txt_select_list_contact;
	Button btnBack, btnRight, btnUpdate, btnDelete;
	DataStore mDataStore;
	SchedulerSMSItem smsItem;
	Calendar dateTime;
	SimpleDateFormat dateFormatter;
	private ProgressDialog mProgressBar = null;
	private static final int DIALOG_WEEK = 1;
	private static final int DIALOG_TIME = 2;
	private static final int DIALOG_DATE = 3;
	private static final int RESURT_OK = 4;
	private static final int RESURT_NO = 5;
	private static final int RESURT_NO_CONTACT = 6;
	private static final int DELETE_SUCCESS = 7;
	private static final int DELETE_FAIL = 8;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_update_sms);
		mActivity = this;
		mContext = this;
		DataStore.init(mContext);
		mDataStore = DataStore.getInstance();
		dateTime = Calendar.getInstance();
		dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
		b = getIntent().getExtras();
		if (b != null) {
			smsItem = (SchedulerSMSItem) b.getSerializable("scheduler");
		} else {
			return;
		}
		btnBack = (Button) findViewById(R.id.btn_left);
		btnRight = (Button) findViewById(R.id.btn_right);
		btnRight.setVisibility(Button.GONE);
		TextView txt_title = (TextView) findViewById(R.id.txt_title);
		txt_title.setText(getString(R.string.txt_setting_sms));
		txt_select_week = (TextView) findViewById(R.id.txt_select_week);
		txt_select_week.setText(smsItem.week);
		txt_select_time = (TextView) findViewById(R.id.txt_select_time);
		txt_select_time.setText(smsItem.time);
		txt_select_sms = (TextView) findViewById(R.id.txt_select_sms);
		txt_select_sms.setText(smsItem.message);
		txt_select_contact = (TextView) findViewById(R.id.txt_select_contact);
		txt_select_list_contact = (TextView) findViewById(R.id.txt_select_list_contact);
		txt_select_list_contact.setText(smsItem.phone);
		txt_select_week.setOnClickListener(onClickWeekListener);
		txt_select_time.setOnClickListener(onClickTimeListener);
		txt_select_sms.setOnClickListener(onClickPatentListener);
		txt_select_contact.setOnClickListener(onClickContactListener);
		btnUpdate = (Button) findViewById(R.id.btn_update);
		btnDelete = (Button) findViewById(R.id.btn_delete);

		btnUpdate.setOnClickListener(onClickUpdateListener);
		btnDelete.setOnClickListener(onClickDeleteListener);
		btnBack.setOnClickListener(onClickBackListener);

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {
			if (resultCode == RESULT_OK) {
				String result = data.getStringExtra("phone");
				txt_select_list_contact.setText(result);
			}
			if (resultCode == RESULT_CANCELED) {
				txt_select_list_contact.setText("");
			}
		}
		if (requestCode == 2) {
			if (resultCode == RESULT_OK) {
				String result = ((Sms) b.getSerializable("sms")).message;
				txt_select_sms.setText(result);
			}
		}
	}

	OnClickListener onClickBackListener = new OnClickListener() {

		public void onClick(View v) {
			onBackPressed();
		}
	};

	OnClickListener onClickDateListener = new OnClickListener() {

		public void onClick(View v) {
			showDialog(DIALOG_DATE);
		}
	};
	OnClickListener onClickTimeListener = new OnClickListener() {

		public void onClick(View v) {
			showDialog(DIALOG_TIME);
		}
	};
	OnClickListener onClickWeekListener = new OnClickListener() {

		public void onClick(View v) {
			showDialog(DIALOG_WEEK);
		}
	};
	OnClickListener onClickContactListener = new OnClickListener() {

		public void onClick(View v) {
			Intent i = new Intent(mContext, ContactActivity.class);
			startActivityForResult(i, 1);
		}
	};
	OnClickListener onClickPatentListener = new OnClickListener() {

		public void onClick(View v) {
			// Intent i = new Intent(mContext,SMSPatentDialogActivity.class);
			// startActivityForResult(i, 2);
		}
	};

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			hideLoadingControl();
			switch (msg.what) {
			case RESURT_OK:
				onBackPressed();
				Toast.makeText(mContext,
						getString(R.string.txt_update_thanh_cong),
						Toast.LENGTH_SHORT).show();
				break;
			case RESURT_NO:
				onBackPressed();
				Toast.makeText(mContext,
						getString(R.string.txt_update_that_bai),
						Toast.LENGTH_SHORT).show();
				break;
			case RESURT_NO_CONTACT:
				Toast.makeText(mContext,
						getString(R.string.txt_select_contact),
						Toast.LENGTH_SHORT).show();
				break;
			case DELETE_FAIL:
				onBackPressed();
				Toast.makeText(mContext, getString(R.string.delete_fail),
						Toast.LENGTH_SHORT).show();
				break;
			case DELETE_SUCCESS:
				onBackPressed();
				Toast.makeText(mContext, getString(R.string.delete_success),
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	OnClickListener onClickDeleteListener = new OnClickListener() {

		public void onClick(View v) {
			showLoadingControl();
			Thread dataInitializationThread = new Thread() {
				public void run() {
					try {
						if (mDataStore.removeListSMS(smsItem)) {
							mHandler.sendEmptyMessage(DELETE_SUCCESS);
						} else {
							mHandler.sendEmptyMessage(DELETE_FAIL);
						}
					} catch (Exception ex) {
						mHandler.sendEmptyMessage(DELETE_FAIL);
					}
				}
			};
			dataInitializationThread.start();
		}
	};

	OnClickListener onClickUpdateListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			showLoadingControl();
			Thread dataInitializationThread = new Thread() {
				public void run() {
					String phone = txt_select_list_contact.getText().toString();
					String message = txt_select_sms.getText().toString();
					String week = txt_select_week.getText().toString();
					String time = txt_select_time.getText().toString();
					try {
						if (!phone.equals("")) {
							SchedulerSMSItem s = new SchedulerSMSItem();
							s.id = smsItem.id;
							s.name = "SMS";
							s.phone = phone;
							s.message = message;
							s.week = week;
							s.time = time;
							s.status = 1;
							boolean checkUpdate = mDataStore.updateScheduler(s);
							if (checkUpdate) {								
								mHandler.sendEmptyMessage(RESURT_OK);
							} else {
								mHandler.sendEmptyMessage(RESURT_NO);
							}
						} else {
							mHandler.sendEmptyMessage(RESURT_NO_CONTACT);
						}
					} catch (Exception ex) {
						mHandler.sendEmptyMessage(RESURT_NO);
					}
				};
			};
			dataInitializationThread.start();
		}
	};

	private void showLoadingControl() {
		mProgressBar = ProgressDialog.show(mActivity, "",
				getString(R.string.loading_default), true);

	}

	private void hideLoadingControl() {
		if (mProgressBar != null && mProgressBar.isShowing())
			mProgressBar.dismiss();

	}

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		final CharSequence[] items = { getString(R.string.txt_thu_2),
				getString(R.string.txt_thu_3), getString(R.string.txt_thu_4),
				getString(R.string.txt_thu_5), getString(R.string.txt_thu_6),
				getString(R.string.txt_thu_7), getString(R.string.txt_chu_nhat) };
		final boolean[] itemsChecked = new boolean[items.length];
		switch (id) {
		case DIALOG_DATE:
			return new DatePickerDialog(this, new OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker view, int year,
						int monthOfYear, int dayOfMonth) {
					dateTime.set(year, monthOfYear, dayOfMonth);
					txt_select_time.setText(dateFormatter.format(dateTime
							.getTime()));
				}
			}, dateTime.get(Calendar.YEAR), dateTime.get(Calendar.MONTH),
					dateTime.get(Calendar.DAY_OF_MONTH));
		case DIALOG_TIME:
			return new TimePickerDialog(this, new OnTimeSetListener() {
				@Override
				public void onTimeSet(TimePicker view, int hour, int minute) {
					txt_select_time.setText(new StringBuilder()
							.append(pad(hour)).append(":").append(pad(minute)));
				}
			}, dateTime.get(Calendar.HOUR_OF_DAY), dateTime
					.get(Calendar.MINUTE), false);
		case DIALOG_WEEK:
			return new AlertDialog.Builder(this)
					.setIcon(R.drawable.ic_launcher)
					.setTitle(R.string.txt_week_title)
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									StringBuilder sb = new StringBuilder();
									int k = 0;
									for (int i = 0; i < items.length; i++) {
										if (itemsChecked[i]) {
											k++;
											if (k != 1)
												sb.append(",");
											sb.append(items[i]);
										}
									}
									txt_select_week.setText(sb);
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							})
					.setMultiChoiceItems(items, itemsChecked,
							new DialogInterface.OnMultiChoiceClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which, boolean isChecked) {
									Toast.makeText(
											getBaseContext(),
											items[which]
													+ " "
													+ (isChecked ? getString(R.string.txt_da_chon)
															: getString(R.string.txt_bo_chon)),
											Toast.LENGTH_SHORT).show();
								}
							}).create();
		}

		return null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			finish();
			break;
		default:
			finish();
			break;
		}
		return true;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
}